package com.evan.kdl.test.day02;

import cn.hutool.core.date.StopWatch;
import com.evan.kdl.test.entity.MyTask;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author huangzhongliang
 * 本机8核16线程
 * @time 2024/01/18 0:18
 */
public class CompletableFutureDemo2 {
    public static void main(String[] args) {
        //    并行流不能控制线程数
        //逻辑处理器数量  16
        //final int N_CPU = Runtime.getRuntime().availableProcessors();
        //    模拟18个任务
        //    含头不含尾（0-17）
        List<MyTask> myTasks = IntStream.range(0, 18).mapToObj(item -> new MyTask(1)).collect(Collectors.toList());
        final int N_CPU = Runtime.getRuntime().availableProcessors();
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(myTasks.size(), N_CPU * 2));
        try {
            StopWatch sw = new StopWatch();
            sw.start();
            List<CompletableFuture<Integer>> futures = myTasks.stream().map(myTask -> CompletableFuture.supplyAsync(myTask::doWork, executor)).collect(Collectors.toList());
            List<Integer> results = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
            sw.stop();
            System.err.printf("processed %d tasks cost %.2f second", myTasks.size(), sw.getTotalTimeSeconds());
        } finally {
            executor.shutdown();
        }
    }
}
